<template>
  <div class="w h over-h">
    <div class="category-title a-i-c f-s dialog-page-title">
      <el-button type='text' icon="ArrowLeft" @click="goBackToPage">返回</el-button>
      <div class="m-l10">
        {{ params.isEdit ? '团队成员编辑' : '团队成员新增' }}
      </div>
    </div>
    <div class="w f-c a-i-c" :style="normalBodyHeight">
      <div style="min-height:480px">
        <div class="m-b5">
          <el-radio-group v-model="appendType">
            <el-radio-button :label="1">选择已注册用户绑定</el-radio-button>
            <el-radio-button :label="0">{{ isSelectAppend ? '设置已选择用户权限' : `直接${params.isEdit ? '编辑' : '添加'}添加用户` }}
            </el-radio-button>
          </el-radio-group>
        </div>
        <div v-show="isAddUser">
          <lm-form :ref="editFormRefKey" inline label-width="120px" class="lm-w lm-h" :layout="editFromLayout"
            v-model="editForm">
            <template #meta>
              <span class="c7">
                Meta:{{ metaString }}
              </span>
            </template>
          </lm-form>
          <div class="lm-w lm-h lm-f-s">
            <div class="lm-w-120 lm-h"></div>
            <el-button type="primary" @click="submit">提交</el-button>
            <el-button type="danger" @click="reset" plain>重置</el-button>
            <el-button type="primary" @click="goBackToPage()" plain>返回</el-button>
          </div>
        </div>
        <div v-if="!isAddUser">
          <div class="w" style="height:calc(100% - 80px)">
            <div class="w f-s a-i-c m-b4">
              <el-input v-model="searchForm.jobNumber" clearable class="w-120 m-l2" placeholder="工号"></el-input>
              <el-input v-model="searchForm.mobile" clearable class="w-120 m-l2" placeholder="手机号码"></el-input>
              <el-input v-model="searchForm.userName" clearable class="w-120 m-l2" placeholder="用户名"></el-input>
              <el-input v-model="searchForm.name" clearable class="w-120 m-l2" placeholder="姓名"></el-input>
              <el-button icon="search" class="m-l2" type="primary" @click="getOtherUserList">查询</el-button>
            </div>
            <div class="w" style="height:calc(100% - 80px);min-height:400px">
              <el-table height="100%" :data="otherUserListData" stripe border>
                <el-table-column label="姓名" prop="name" width="120px"></el-table-column>
                <el-table-column label="工号" prop="jobNumber" width="120px"></el-table-column>
                <el-table-column label="用户名" prop="userName" width="120px"></el-table-column>
                <el-table-column label="手机号码" prop="mobile" width="110px"></el-table-column>
                <el-table-column label="邮箱" prop="email" width="180px"></el-table-column>
                <el-table-column label="操作" fixed="right">
                  <template #default="{ row }">
                    <el-button type="text" @click="bandTeam(row)" title="绑定为当前团队">绑定</el-button>
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </div>
          <div class="f-e p2">
            <el-pagination small background v-model:current-page="current" :page-size="size" layout="prev, pager, next"
              @size-change="pageSizeHandler" @current-change="pageCurrentHandler" :total="total" class="mt-4" />
          </div>
        </div>

      </div>
    </div>
  </div>
</template>

<script lang="ts">
import frameProperty from '@/mixins/frame-property'
import { Team, type TeamInfo } from '@/apis/team/index'
import { Role, type RoleInfo } from '@/apis/role/index'
import { RequestCode } from '@/server/base'
import { ValidateFieldsError } from 'async-validator'

export default {
  name: 'TeamEdit',
  mixins: [frameProperty],
  props: {
    goBackToPage: Function,
    params: [Object, Array]
  } as any,
  data() {
    return {
      editFormRefKey: 'teamModifyRef',
      appendType: 1,

      editForm: {} as {} | TeamInfo | any,

      searchForm: {
        name: '',
        jobNumber: '',
        userName: '',
        mobile: ''
      },
      current: 1,
      size: 10,
      total: 0,
      otherUserListData: [] as any[],

      isSelectAppend: false,
      roleOptions: []
    }
  },
  computed: {
    modifyInfo() {
      return this.params.row
    },
    //是否是添加用户 true 是 false 绑定用户
    isAddUser(): boolean {
      return this.appendType == 0
    },
    editFromLayout() {
      return [
        {
          prop: 'name',
          label: '姓名',
          type: 'input',
          itemClass: 'column_1',
          disabled: this.isSelectAppend,
          clearable: true,
          required: true
        },
        {
          prop: 'username',
          label: '用户名',
          type: 'input',
          itemClass: 'column_1',
          disabled: this.isSelectAppend,
          clearable: true,
          required: true
        },
        {
          prop: 'jobNumber',
          label: '工号',
          type: 'input',
          itemClass: 'column_1',
          disabled: this.isSelectAppend,
          clearable: true,
          required: true
        },
        {
          prop: 'roleId',
          label: '角色',
          type: 'select',
          itemClass: 'column_1',
          required: true,
          clearable: true,
          filterable: true,
          options: this.roleOptions
        },
        {
          prop: 'mobile',
          label: '电话',
          type: 'input',
          itemClass: 'column_1',
          disabled: this.isSelectAppend,
          regex: /(^1[0-9]{10}$)?/,
          // required: true,
          clearable: true
        },
        {
          prop: 'email',
          label: '邮箱',
          type: 'input',
          itemClass: 'column_1',
          disabled: this.isSelectAppend,
          regex: /^[^@]*[@][a-zA-Z]*[.]?[a-zA-Z]*/,
          clearable: true
          // required: true,
        }
      ]
    }
  },
  methods: {
    getRoleData() {
      const index = this.editFromLayout.findIndex((item: { prop: string }) => item.prop == 'roleId')
      if (index < 0) {
        return
      }
      Role.list()
        .then((res: RequestCode) => {
          this.roleOptions =
            // this.editFromLayout[index].options =
            res.data.map((item: { id: string | number; name: string | number }) => {
              return { value: item.id, label: item.name }
            })
        })
        .catch(e => { })
    },

    getDetailById() {
      if (!this.modifyInfo) {
        return
      }
      // this.editForm.teamId = this.modifyInfo.id;
      const { id, ...form } = this.modifyInfo
      this.editForm = form
      this.editForm.userId = id
    },
    bandTeam(row: any) {
      this.isSelectAppend = true
      const { id, createTime, ..._row } = row
      this.editForm = { ..._row }
      this.editForm.teamId = this.modifyInfo.teamId
      this.editForm.userId = id
      this.appendType = 0
      setTimeout(() => {
        this.submit(false)
      }, 600)
    },
    savePersonTeamInfo(isGoBack: boolean = true) {
      const method = this.isSelectAppend
        ? Team.appendTeamPersonInfo
        : this.params.isEdit
          ? Team.modifyTeamPersonInfo
          : Team.appendTeamPersonInfo
      method(this.editForm)
        .then((res: RequestCode) => {
          this.showMessage({ type: 'success', message: '操作成功！' })
          this.isSelectAppend = false
          if (isGoBack) {
            this.goBackToPage(true)
          }
        })
        .catch((error: any) => { })
    },
    //验证数据
    submit(isGoBack: boolean = true) {
      const editFormRef = this.$refs[this.editFormRefKey] as any
      editFormRef.validate((isValid: boolean, invalidFields?: ValidateFieldsError) => {
        if (!isValid) {
          //滚动到未通过校验的字段
          if (invalidFields && Object.keys(invalidFields).length > 0) {
            editFormRef.scrollToField(Object.keys(invalidFields)[0])
          }
          return
        }
        this.savePersonTeamInfo(isGoBack)
      })
    },
    getOtherUserList() {
      const params = {
        teamId: this.modifyInfo.teamId,
        size: this.size,
        current: this.current,
        ...this.searchForm
      }

      Team.otherUserList(params)
        .then((res: RequestCode) => {
          const { records, current, size, total } = res.data
          this.otherUserListData = records
          this.current = current
          this.size = size
          this.total = total
        })
        .catch(() => { })
    },

    pageCurrentHandler(val: number) {
      this.current = val
      this.getOtherUserList()
    },
    pageSizeHandler(val: number) {
      this.size = val
      this.current = 1
      this.getOtherUserList()
    },
    //重置
    reset() {
      this.editForm = {}
    }
  },
  created() {
    this.$nextTick(() => {
      this.getRoleData()
      this.getDetailById()
    })
  }
}
</script>

<style scoped></style>